<template>
  <div class="da-list">
    <Breadcrumb>
      <BreadcrumbItem v-for="(name, i) in breadcrumb" :key="i">{{ name }}</BreadcrumbItem>
    </Breadcrumb>
    <div class="list-title">查询条件</div>
    <Row type="flex">
      <Form ref="formInline" :model="formInline" inline :label-width="0" label-position="left">
        <FormItem prop="status" label="">
          <Select v-model="formInline.status" placeholder="全部机构状态" style="minWidth:162px" filterable clearable>
            <Option v-for="item in MerchantStatus" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="type" label="">
          <Select v-model="formInline.type" placeholder="全部机构类型" style="minWidth:162px" filterable clearable>
            <Option v-for="item in MerchantType" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="merchantCompanyId" label="">
          <Select v-model="formInline.merchantCompanyId" placeholder="全部商户" style="minWidth:162px" filterable clearable>
            <Option v-for="item in companyList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="provinceCode" label="">
          <Cascader ref="cascader" :data="pcList" v-model="depc" @on-change="selectPc" :load-data="loadData" placeholder="请选择省市区" style="width: 200px;"></Cascader>
        </FormItem>
        <FormItem prop="date" label="">
          <DatePicker type="daterange" @on-change="selectDate" ref="datePicker" placeholder="请选择日期" style="width: 200px;"></DatePicker>
        </FormItem>
        <FormItem label="" prop="searchContent">
          <Input type="text" v-model="formInline.searchContent" placeholder="分销机构名称" clearable style="width: 300px;"/>
        </FormItem>
<!--        <FormItem label="" prop="isQFUser" v-if="false">-->
<!--          <IsQfUser v-model="formInline.isQFUser" placeholder="是否巧房用户" />-->
<!--        </FormItem>-->
        <div class="form-but">
          <Button type="success" @click="getList">查询</Button>&nbsp;&nbsp;
          <Button @click="handleReset('formInline')">清空</Button>
        </div>
      </Form>
    </Row>
    <div>
      <Button type="primary" ghost @click="newChannel" class="add">新增</Button>
      <Table class="list-table"
        stripe
        border
        ref="selection"
        :columns="columns"
        :data="dataList"
        @on-select="selectOne"
        @on-select-all="selectAll"
        @on-select-cancel="cancelOne"
        @on-select-all-cancel="cancelAll"
      ></Table>
      <div class="table-page">
        <div>
          <Button type="primary" ghost :disabled="!ids.length" @click="batchEnable()">批量启用商户</Button>&nbsp;&nbsp;
          <Button type="warning" ghost :disabled="!ids.length" @click="batchDisabled()">批量禁用商户</Button>&nbsp;&nbsp;
          <Button type="error" ghost :disabled="!ids.length" @click="batchDelete()">批量删除商户</Button>
        </div>
        <Page :total="total" show-sizer show-elevator show-total @on-change="changePageNum" @on-page-size-change="changePageSize" />
      </div>
    </div>
  </div>
</template>

<script>
import { formatTime } from '@/utils'
import Api from '@/api'
// import IsQfUser from '@/components/IsQfUser.vue';

const commonApi = Api.Common
const distributionApi = Api.Distribution
const reportApi = Api.report
const companyApi = Api.Company

export default {
  name: 'login',
  components: {
    // IsQfUser
  },
  data() {
    return {
      breadcrumb: ['合作机构管理', '分销机构管理'],
      formInline: {
        status: '',
        type: '',
        merchantCompanyId: '',
        merchantCode: '',
        searchContent: '',
        createTimeEnd: '',
        createTimeStart: '',
        province: '',
        city: '',
        zone: '',
        // isQFUser: '-1',
      },
      pcList: [],
      depc: [],
      companyList: [],
      MerchantStatus: [
        {
          label: '启用',
          value: '2'
        },
        {
          label: '禁用',
          value: '3'
        },
      ],
      MerchantType: [
        {
          label: '中介',
          value: 1
        },
      ],
      statusList: [
        {
          label: '不开通',
          value: '0'
        },
        {
          label: '开通',
          value: '1'
        }
      ],
      sfList: [
        {
          label: '是',
          value: '1'
        },
        {
          label: '否',
          value: '0'
        }
      ],
      dataList: [],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '分销机构名称',
          key: 'companyName',
          minWidth: 200,
          tooltip: true
        },
        {
          title: '机构类型',
          key: 'companyType',
          minWidth: 120
        },
        // {
        //   title: '巧房用户',
        //   key: 'isQFUser',
        //   minWidth: 80,
        //   render: (h, params) => (
        //     h('div', {}, params.row.status === '1' ? '是' : '否')
        //   )
        // },
        {
          title: '所属商户',
          key: 'merchantCompanyId',
          minWidth: 180,
          tooltip: true,
          render: (h, params) => (
            h('span', {}, this.companyMap[params.row.merchantCompanyId])
          )
        },
        {
          title: '渠道经理',
          key: 'partnerInfoName',
          minWidth: 120
        },
        {
          title: '位置',
          key: 'address',
          minWidth: 200,
          tooltip: true,
        },
        {
          title: '创建时间',
          key: 'createTime',
          minWidth: 200,
          render: (h, params) => (
            h('div', {}, formatTime(params.row.createTime, 'second'))
          )
        },
        {
          title: '状态',
          key: 'status',
          minWidth: 120,
          render: (h, params) => (
            h('div', {}, params.row.status === '2' ? '启用' : '禁用')
          )
        },
        {
          title: '操作',
          key: 'operate',
          minWidth: 250,
          fixed: 'right',
          render: (h, params) => (
            h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.$store.commit('fixTag', { label: '编辑分销机构', url: 'updateAgencies?id=' + params.row.id, path: 'updateAgencies' })
                    this.$router.push({ path: '/updateAgencies?id=' + params.row.id })
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: params.row.status === '2' ? 'warning' : 'success',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: params.row.status === '2' ? '禁用商户' : '启用商户',
                      content: '确定' + params.row.status === '2' ? '禁用商户?' : '启用商户?',
                      onOk: () => {
                        if (params.row.status === '2') {
                          this.prohibit(params.row.id)
                        } else {
                          this.enable(params.row.id)
                        }
                      }
                    })
                  }
                }
              }, params.row.status === '2' ? '禁用' : '启用'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  display: params.row.status === '2' ? 'none' : 'inline-block',
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除商户',
                      content: '确定删除商户？',
                      onOk: () => { this.deleteMerchant(params.row.id) }
                    })
                  }
                }
              }, '删除'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  display: params.row.isBindV10 && params.row.status === '2' ? 'inline-block' : 'none',
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '推送楼盘',
                      content: '确定推送此分销商绑定的商户所有在售楼盘给此分销商？',
                      onOk: () => { this.pushPremisesToV10(params.row.merchantCompanyId, params.row.id, null) }
                    })
                  }
                }
              }, '推送楼盘')
            ])
          )
        }
      ],
      total: 0,
      page: {
        pageNum: 1,
        pageSize: 10
      },
      ids: [],
      companyMap: {}
    }
  },
  methods: {
    cancelAll(selection) {
      this.ids = []
    },
    cancelOne(selection, row) {
      const i = this.ids.indexOf(row.id)
      this.ids.splice(i, 1)
    },
    selectAll(selection) {
      this.ids = []
      this.ids = selection.map(item => {
        return item.id
      })
    },
    selectOne(selection, row) {
      this.ids.push(row.id)
    },
    newChannel() {
      this.$store.commit('fixTag', { label: '新增分销机构', url: 'newAgencies' })
      this.$router.push({ path: '/newAgencies' })
    },
    // 批量启用
    async batchEnable() {
      const { responseCode, responseMessage, responseType } = await this.$request(distributionApi.batchEnableCompany, { ids: this.ids })
      if (responseCode === '1') {
        this.$Message.success('启用成功！')
        this.page = { pageNum: 1, pageSize: 10 }
        this.getList()
        this.ids = []
      } else if (responseType === 'ERROR') {
        this.$Message.error(responseMessage)
      } else {
        this.$Message.error('启用失败！')
      }
    },
    // 批量禁用
    async batchDisabled() {
      const { responseCode, responseMessage, responseType } = await this.$request(distributionApi.batchDisableCompany, { ids: this.ids })
      if (responseCode === '1') {
        this.$Message.success('禁用成功！')
        this.page = { pageNum: 1, pageSize: 10 }
        this.getList()
        this.ids = []
      } else if (responseType === 'ERROR') {
        this.$Message.error(responseMessage)
      } else {
        this.$Message.error('禁用失败！')
      }
    },
    // 批量删除
    async batchDelete() {
      const { responseCode, responseMessage, responseType } = await this.$request(distributionApi.batchDeleteCompany, { ids: this.ids })
      if (responseCode === '1') {
        this.$Message.success('删除成功！')
        this.page = { pageNum: 1, pageSize: 10 }
        this.getList()
        this.ids = []
      } else if (responseType === 'ERROR') {
        this.$Message.error(responseMessage)
      } else {
        this.$Message.error('删除失败！')
      }
    },
    async prohibit(id) {
      const { responseCode, responseMessage, responseType } = await this.$request(distributionApi.disableCompany, { id })
      if (responseCode === '1') {
        this.$Message.success('禁用成功！')
        this.page = { pageNum: 1, pageSize: 10 }
        this.getList()
      } else if (responseType === 'ERROR') {
        this.$Message.error(responseMessage)
      } else {
        this.$Message.error('禁用失败！')
      }
    },
    async enable(id) {
      const { responseCode, responseMessage, responseType } = await this.$request(distributionApi.enableCompany, { id })
      if (responseCode === '1') {
        this.$Message.success('启用成功！')
        this.page = { pageNum: 1, pageSize: 10 }
        this.getList()
      } else if (responseType === 'ERROR') {
        this.$Message.error(responseMessage)
      } else {
        this.$Message.error('启用失败！')
      }
    },
    async deleteMerchant(id) {
      const { responseCode, responseMessage, responseType } = await this.$request(distributionApi.deleteCompany, { id })
      if (responseCode === '1') {
        this.$Message.success('删除成功！')
        this.page = { pageNum: 1, pageSize: 10 }
        this.getList()
      } else if (responseType === 'ERROR') {
        this.$Message.error(responseMessage)
      } else {
        this.$Message.error('删除失败！')
      }
    },
    async pushPremisesToV10(devCompanyId, agentCompanyId, premisesIds) {
      const { responseCode, responseMessage, responseType } = await this.$request(reportApi.pushPremisesToV10, { devCompanyId, agentCompanyId, premisesIds })
      if (responseCode === '1') {
        this.$Message.success('推送成功！')
        this.page = { pageNum: 1, pageSize: 10 }
        this.getList()
      } else if (responseType === 'ERROR') {
        this.$Message.error(responseMessage)
      } else {
        this.$Message.error('推送失败！')
      }
    },
    selectDate(date) {
      this.formInline.createTimeStart = date[0]
      this.formInline.createTimeEnd = date[1]
    },
    selectPc(value, selectedData) {
      this.formInline.province = value[0]
      this.formInline.city = value[1]
      this.formInline.zone = value[2]
    },
    async getProvince() {
      const { responseCode, data } = await this.$request(commonApi.listProvince)
      if (responseCode === '1') {
        data.forEach((item, index) => {
          item.loading = false
          item.children = []
        })
        this.pcList = data
      }
    },
    loadData(item, callback) {
      const len = item.__label.split('/').length
      item.loading = true
      setTimeout(async () => {
        const { responseCode, data } = await this.$request(commonApi.listCity, { provinceId: item.value })
        if (responseCode === '1') {
          if (len < 2) {
            data.forEach((city, index) => {
              city.loading = false
              city.children = []
            })
          }
          item.children = data
        }
        item.loading = false
        callback()
      }, 500)
    },
    // 分页变化
    changePageNum(pageNum) {
      this.getList({ pageNum })
    },
    // 条数变化
    changePageSize(pageSize) {
      this.getList({ pageSize })
    },
    async handleReset(name) {
      this.$refs[name].resetFields()
      this.$refs.datePicker.handleClear()
      this.$refs.cascader.clearSelect()
      this.formInline.createTimeStart = ''
      this.formInline.createTimeEnd = ''
      this.page = {
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    async getList(paramsPage = null) {
      let pageNum
      let pageSize
      let page
      const statePage = this.page
      if (paramsPage) {
        pageNum = paramsPage.pageNum || statePage.pageNum
        pageSize = paramsPage.pageSize || statePage.pageSize
        page = { pageNum, pageSize }
        this.page = { pageNum, pageSize }
      } else {
        page = statePage
      }
      const formInline = this.formInline
      const value = {}
      Object.keys(formInline).forEach(key => {
        if (formInline[key]) {
          value[key] = formInline[key]
        }
      })
      const params = {
        page,
        ...value
      }
      const { responseCode, data } = await this.$request(distributionApi.listCompany, params)
      if (responseCode === '1') {
        data.list.forEach((item, index) => {
          const map = {
            1: '中介',
            20: '开发商',
            30: '总代公司',
            40: '试用商户'
          }
          item.companyType = map[item.companyType]
        })
        this.dataList = data.list
        this.total = data.totalCount
      }
    },
    async getCompanyList() {
      const { responseCode, data } = await this.$request(companyApi.listOptionCompany)
      if (responseCode === '1') {
        const map = {}
        data.forEach((item, index) => {
          map[item.value] = item.label
        })
        this.companyMap = map
        this.companyList = data
      }
    },
  },
  mounted() {
    this.getCompanyList()
    this.getProvince()
    this.getList()
  },
}
</script>
<style lang="scss" scoped>
.da-list {
  .ivu-form-item {
    margin-right: 20px;
  }
  .form-but {
    display: inline-block;
    margin-bottom: 24px;
  }
  .list-title {
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    color: #333;
  }
  .add {
    margin-bottom: 10px;
  }
  .table-page {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
  }
}
</style>
